package org.danger.t7.common.ws.cloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@ConditionalOnClass(StringRedisTemplate.class)
public class WsRedisBus {
    public static final String CHANNEL = "/fkws/channel";
    public static final String BROKER_UID = "0";
    public static final String SPLITER = "o>>o";
    @Autowired
    protected StringRedisTemplate redisTemplate;


    public void sendMessage(String fromUid, String toUid, String message) {
//        Map<String, Object> map = new HashMap<>(3);
//        map.put("action", "send");
//        map.put("dst", dst);
//        map.put("data", message);
        if (!StringUtils.hasLength(fromUid)) {
            fromUid = WsRedisBus.BROKER_UID;
        }
        String m = String.format(fromUid + SPLITER + toUid + SPLITER + message);
        // 发布消息到redis频道上 redis转发到订阅的各个socket实例上 收到信息 根据标识 获取到session 发给自己对应的客户端
        // 对应命令："PUBLISH" "/ws/channel" "sendo>>oxxxxxo>>orrrrrr"
        redisTemplate.convertAndSend(CHANNEL, m);
    }

}
